package com.advertisementsystem.Servie.Impl;

import com.advertisementsystem.Dto.AssignRoleDTO;
import com.advertisementsystem.Mapper.PermissionMapper;
import com.advertisementsystem.Mapper.RoleMapper;
import com.advertisementsystem.Mapper.UserRoleMapper;
import com.advertisementsystem.Servie.UserRoleService;
import com.advertisementsystem.entity.Permission;
import com.advertisementsystem.entity.Role;
import com.advertisementsystem.entity.UserRole;
import com.advertisementsystem.vo.UserRoleVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRoles(AssignRoleDTO assignRoleDTO) {
        // 删除原有角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, assignRoleDTO.getUserId());
        userRoleMapper.delete(wrapper);

        // 保存新角色
        for (Long roleId : assignRoleDTO.getRoleIds()) {
            UserRole userRole = new UserRole();
            userRole.setUserId(assignRoleDTO.getUserId());
            userRole.setRoleId(roleId);
            userRole.setCreatedTime(LocalDateTime.now());
            userRoleMapper.insert(userRole);
        }
    }

    @Override
    public UserRoleVO getUserRoles(Long userId) {
        UserRoleVO vo = new UserRoleVO();
        vo.setUserId(userId);

        // 获取用户角色
        List<Role> roles = roleMapper.selectRolesByUserId(userId);
        vo.setRoles(roles);

        // 获取用户权限
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(userId);
        vo.setPermissions(permissions.stream()
                .map(Permission::getCode)
                .collect(Collectors.toList()));

        return vo;
    }
}
